package com.kly.user.task.v2.appflyers;

import cn.hutool.core.net.NetUtil;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.nacos.api.config.annotation.NacosValue;
import com.fqgj.common.utils.CollectionUtils;
import com.fqgj.common.utils.StringUtils;
import com.fqgj.log.factory.LogFactory;
import com.fqgj.log.interfaces.Log;
import com.kly.user.db.dao.UserTaskDetailDao;
import com.kly.user.db.entity.UserTaskDetailEntity;
import com.kly.user.task.enums.TaskTypeEnum;
import com.kly.user.utils.LittleOrangeService;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

/**
 * appFlyer推送失败重试任务
 */
@Service
public class PushToAppFlyerRetryTask {

    private static Log logger = LogFactory.getLog(PushToAppFlyerRetryTask.class);
    @NacosValue(value = "${task.job.executor.ip}", autoRefreshed = true)
    private String taskJobExecutor;
    @NacosValue(value = "${push.to.af.switch:true}", autoRefreshed = true)
    private Boolean pushToAfSwitch;
    private String localIP = NetUtil.getLocalhostStr();
    @NacosValue(value = "${appsflyer.auth}", autoRefreshed = true)
    private String auth;
    @Resource
    private UserTaskDetailDao userTaskDetailDao;

    /**
     * 执行频率：10分钟
     */
//    @Scheduled(fixedDelay = 1000 * 120)
    public void run() {
        logger.info("====RepairChatListTask start");
        if (!taskJobExecutor.contains(localIP)) {
            logger.info("=============PushToAppFlyerRetryTask, currentLocalAddress:{}, onlyExecuteTaskIn:{}", localIP, taskJobExecutor);
            return;
        }
        if (!pushToAfSwitch) {
            logger.info("=============PushToAppFlyerRetryTask, pushToAfSwitch:{}", pushToAfSwitch);
            return;
        }

        // 推送appflyers
        pushToAppflyers();



    }

    private void pushToAppflyers() {
        final List<UserTaskDetailEntity> waitingProcessTasks = userTaskDetailDao.queryNeedProcessJobsByType(TaskTypeEnum.PUSH_DATA_TO_APPSFLYER_V2.getCode(), 5);
        if (CollectionUtils.isEmpty(waitingProcessTasks)) {
            return;
        }
        for (UserTaskDetailEntity task : waitingProcessTasks) {
            logger.info("PushToAppFlyerRetryTaskStart===, task:{}", JSONObject.toJSONString(task));
            Integer status = task.getStatus();
            try {
                final String result = retryPushToAf(task);
                if (StringUtils.isNotEmpty(result) && result.equals("ok")) {
                    status = 1;
                }

                userTaskDetailDao.updateTask(task.getId(), status, result);
                logger.info("PushToAppFlyerRetryTaskEnd===, task:{}, result:{}", JSONObject.toJSONString(task), result);

            } catch (Exception e) {
                userTaskDetailDao.updateTask(task.getId(), status, e.getMessage());
                logger.error("PushToAppFlyerRetryTaskError, task:{}", JSONObject.toJSONString(task), e);
            }
        }
    }






    public String retryPushToAf(UserTaskDetailEntity task) {
        final String result = LittleOrangeService.post(task.getCallbackUrl(), auth, task.getRequest());
        logger.info("PushDataToAppsFlyerSuccess, body:{}, result:{}",  task.getRequest(), result);
        return result;
    }

}